<?php

/**
 * Description of ContentUserRequests
 *
 * @author Honza, Kevin 
 */
class ContentUserRequests implements IMainBodyWithInteraction {

  private $showTable = true;

  public function action() {
    if (isset($_GET['a'])) {
      if ($_GET['a'] == 'cancel') {
        $reqID = addslashes($_GET['ida']);
		//
        $sql = 'update ' . TBL_REQUESTS . " set state = 'neplatný' where id_request = " . $reqID;
        DB::sql($sql);
      }
    }
  }

  public function applyForm($formID = NULL) {
    
  }
//getContent function called automatically
  public function getContent() {
    $content = '';
    $content .= '<h2>My requests</h2>';
    $this->action();
    $content .= $this->getTable();
    return $content;
  }

  public function getForm($formID = NULL, $error = NULL) {
    
  }

  public function getSubmitedForm() {
    
  }
  
// get table to show table details
  public function getTable($tableID = NULL) {
    if ($this->showTable) {
      $auth = Auth::getInstance();
      $identity = $auth->getIdentity();
      $userID = $identity['id'];

      $cols = 'id_request,title, DATE_FORMAT(date_of_creation, \'%Y-%m-%d\') as date_of_creation, id_book';
      $sql = 'select ' . $cols . ' from ' . TBL_REQUESTS . '';
      $sql .= ' join ' . TBL_BOOKS . ' using (id_book)';
      $sql .= ' where id_user = ' . $userID . ' and state = \'platný\'';
      $sql .= ' order by date_of_creation';


      $result = DB::sql($sql);

      if (empty($result)) {
        return '<p>No requests</p>';
      }
      
      $table = '<table>';
      $table .= '<tr>';
      $table .= '<th>Title</th><th>Date of creation</th><th>Request before you</th><th>Cancel</th>';
      $table .= '</tr>';
      foreach ($result as $row) {
        $reqID = $row['id_request'];
//select count(id_request) - 1 as fronta from library_requests join library_books using (id_book) where id_book = 2 and state = 'platný' and id_request = 1 order by id_request;
        $sql = 'select count(id_request) - 1 as fronta  from ' . TBL_REQUESTS . '';
        $sql .= ' join ' . TBL_BOOKS . ' using (id_book)';
        $sql .= ' where id_book = ' . $row['id_book'] . ' and state = \'platný\'';
        //$sql .= 'and id_request = ' . $idPoz;
        $sql .= ' order by id_request';
        $fronta = DB::sql($sql);

        $table .= '<tr>';
        $table .= '<td>' . $row['title'] . '</td>';
        $table .= '<td>' . $row['date_of_creation'] . '</td>';
        $table .= '<td>' . $fronta[0]['fronta'] . '</td>';
        $table .= '<td><a href="index.php?where=user&subwhere=requests&a=cancel&ida=' . $reqID . '">Cancel</a></td>';
        $table .= '</tr>';
      }
      $table .= '';
      $table .= '</table>';

      return $table;
    }
  }

}

?>
